//
//  VIewControllerHelper.m
//  unicorn
//
//  Created by weiwang on 13-7-21.
//  Copyright (c) 2013年 weiwang. All rights reserved.
//

#import "ViewControllerHelper.h"
#import "MBProgressHUD.h"
#import "RIButtonItem.h"
#import "UIAlertView+Blocks.h"
//#import "UIDefine.h"
#import "UIViewAdditions.h"
#import "UINavigationItemAdditions.h"
#import "NSArray+Safety.h"
#import "NSString+Calculating.h"
#import "UIView+ZYBCustomToast.h"
#import "ZYBUIDefine.h"

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

@interface ViewControllerHelper ()


@end

@implementation ViewControllerHelper
{
    MBProgressHUD *tipHud;
    MBProgressHUD *waitHud;
}

- (UIBarButtonItem *)barWithText:(NSString *)text
                          target:(id)target
                          action:(SEL)action{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    if (text && [text length] > 0){
        [button setTitle:text forState:UIControlStateNormal];
        [button setTitle:text forState:UIControlStateHighlighted];
        [button.titleLabel setFont:kItemTitleFont];
        [button setTitleColor:kTextBarItemColorNormal forState:UIControlStateNormal];
        [button setTitleColor:kTextBarItemColorHilight forState:UIControlStateHighlighted];
        button.showsTouchWhenHighlighted = YES;
    }
    if (target && action) {
        [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    CGSize titleSize = [text stringSizeWithFont:button.titleLabel.font constrainWidth:kScreenWidth];
    if (titleSize.width < 44)
        titleSize.width = 44;
    button.frame = CGRectMake(0, 0, titleSize.width, 44);
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    buttonItem.style = UIBarButtonItemStyleBordered;
    return buttonItem;
}

- (UIBarButtonItem *)barWithImage:(UIImage *)image
                    selectedImage:(UIImage *)selectedImage
                  backgroundImage:(UIImage *)backgroundImage
          selectedBackgroundImage:(UIImage *)selectedBackgroundImage
                           target:(id)target
                           action:(SEL)action
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (image) {
        [button setImage:image forState:UIControlStateNormal];
    }
    if (selectedImage) {
        [button setImage:selectedImage forState:UIControlStateHighlighted];
        [button setImage:selectedImage forState:UIControlStateSelected];
    }
    if (backgroundImage) {
        [button setBackgroundImage:backgroundImage forState:UIControlStateNormal];
    }
    if (selectedBackgroundImage) {
        [button setBackgroundImage:selectedBackgroundImage forState:UIControlStateHighlighted];
        [button setBackgroundImage:selectedBackgroundImage forState:UIControlStateSelected];
    }
    if (target && action) {
        [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }

    CGFloat width = 44;
    CGFloat height = 44;
    if (backgroundImage && image) {
        [button setShowsTouchWhenHighlighted:NO];
        if (backgroundImage.size.width > (image.size.width + 16)) {
            width = backgroundImage.size.width;
        }
        height = backgroundImage.size.height;
    }else if(image) {
        [button setShowsTouchWhenHighlighted:YES];
        
        if (width < image.size.width) {
            width = image.size.width;
        }
        if (height < image.size.height) {
            height = image.size.height;
        }
    }
    button.frame = CGRectMake(0, 0, width, height);
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    buttonItem.style = UIBarButtonItemStyleBordered;
    return buttonItem;
}

- (void)setDefaultBackItemWithImage:(UIImage *)image selectedImage:(UIImage *)selectedImage {
    UIBarButtonItem *leftItem = [self barWithImage:image selectedImage:selectedImage backgroundImage:nil selectedBackgroundImage:nil target:self action:@selector(backClick:)];
    UIButton *itemBtn = leftItem.customView;
#if __IPHONE_11_0
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 11.0f) {
        itemBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 16);
    }
#endif
    [self.ownerViewController.navigationItem addLeftBarButtonItem:leftItem];
}

- (void)setDefaultBackItemWithImage:(UIImage *)image selectedImage:(UIImage *)selectedImage action:(SEL)action {
    UIBarButtonItem *leftItem = [self barWithImage:image selectedImage:selectedImage backgroundImage:nil selectedBackgroundImage:nil target:self.ownerViewController action:action];
    UIButton *itemBtn = leftItem.customView;
#if __IPHONE_11_0
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 11.0f) {
        itemBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 16);
    }
#endif
    [self.ownerViewController.navigationItem addLeftBarButtonItem:leftItem];
}

- (void)setLeftItemImage:(UIImage *)image selectedImage:(UIImage *)selectedImage target:(id)target action:(SEL)action
{
    UIBarButtonItem *leftItem = [self barWithImage:image selectedImage:selectedImage backgroundImage:nil selectedBackgroundImage:nil target:target action:action];
    UIButton *itemBtn = leftItem.customView;
    UIView *customView = [[UIView alloc] initWithFrame:itemBtn.bounds];
    customView.backgroundColor = [UIColor clearColor];
#if __IPHONE_11_0
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 11.0f) {
        itemBtn.left = -16;
    }
#endif
    leftItem.customView = customView;
    [customView addSubview:itemBtn];
    [self.ownerViewController.navigationItem addLeftBarButtonItem:leftItem];
}

- (void)setLeftItemText:(NSString *)text target:(id)target action:(SEL)action {
    UIBarButtonItem *item = [self barWithText:text target:target action:action];
    [self.ownerViewController.navigationItem addLeftBarButtonItem:item];
}

- (void)setRightItemText:(NSString *)text target:(id)target action:(SEL)action{
    UIBarButtonItem *rightItem = [self barWithText:text target:target action:action];
    [self.ownerViewController.navigationItem addRightBarButtonItem:rightItem];
}

- (void)setRightItemImage:(UIImage *)image selectedImage:(UIImage *)selectedImage target:(id)target action:(SEL)action
{
    UIBarButtonItem *rightItem = [self barWithImage:image selectedImage:selectedImage backgroundImage:nil selectedBackgroundImage:nil target:target action:action];
    self.ownerViewController.navigationItem.rightBarButtonItem = rightItem;
}

- (void)setNavgationBarImage:(UIImage *)image
{
    [self.ownerViewController.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}

- (void)setNavgationBarHidden:(BOOL)hidden animated:(BOOL)animated {
    [self.ownerViewController.navigationController setNavigationBarHidden:hidden animated:animated];
}

- (void)setNavgationBarHidden:(BOOL)hidden{
    [self setNavgationBarHidden:hidden animated:YES];
}

- (void)setTabBarHidden:(BOOL)hidden
{
    if (self.ownerViewController.tabBarController.tabBar.hidden == hidden) {
		return;
	}
	
    UIView *contentView;
	
    if ( [[self.ownerViewController.tabBarController.view.subviews objectAtIndexSafely:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.ownerViewController.tabBarController.view.subviews objectAtIndexSafely:1];
    else
        contentView = [self.ownerViewController.tabBarController.view.subviews objectAtIndexSafely:0];
    
    CGFloat height = 0.0f;
    if (hidden)
        height = contentView.bounds.size.height + self.ownerViewController.tabBarController.tabBar.frame.size.height;
    else
        height = contentView.bounds.size.height - self.ownerViewController.tabBarController.tabBar.frame.size.height;
    
	contentView.frame = CGRectMake(contentView.bounds.origin.x,
                                   contentView.bounds.origin.y,
                                   contentView.bounds.size.width,
                                   height);
    
    self.ownerViewController.tabBarController.tabBar.hidden = hidden;
}

- (void)startAnimating {
    [self startAnimatingWithText:@"努力加载中"];
}

- (void)startAnimatingWithText:(NSString *)text {
    [self.ownerViewController.view showLoadingMessage:text];
}

- (void)stopAnimating {
    [self.ownerViewController.view removeLoadingTost];
}

- (void)showMessageOnlyTip:(NSString*)amsg withTipType:(VCShowTipType)type;
{
    if (type == VCShowTipTypeError) {
        [self.ownerViewController.view showErrorMessage:amsg];
    }else if(type == VCShowTipTypeNetError){
        [self.ownerViewController.view showNetErrorWithMessage:amsg];
    }else if (type == VCShowTipTypeSuccess){
        [self.ownerViewController.view showSucceedMessage:amsg];
    }
}

//WebView加载的提示
- (void)showWebviewLoading:(UIView *)webview
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    UILabel *_loadingTipLabel = (UILabel *)[webview viewWithTag:3000];
    UIActivityIndicatorView *_loadingTipIndicator = (UIActivityIndicatorView *)[webview viewWithTag:3001];
    if (_loadingTipLabel == nil) {
        _loadingTipLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        _loadingTipLabel.tag = 3000;
        [webview addSubview:_loadingTipLabel];
    }
    if (nil == _loadingTipIndicator) {
        _loadingTipIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _loadingTipIndicator.tag = 3001;
        [webview addSubview:_loadingTipIndicator];
    }
    
    [_loadingTipLabel setHidden:NO];
    [_loadingTipLabel setText:@"正在加载中..."];
    [_loadingTipLabel setTextAlignment:NSTextAlignmentCenter];
    [_loadingTipLabel setFont:UI_NORMAL_FONT(15)];
    [_loadingTipLabel setBackgroundColor:[UIColor clearColor]];
    [_loadingTipLabel setTextColor:UI_COLOR(0x78, 0x78, 0x78)];
    [_loadingTipLabel sizeToFit];
    [_loadingTipLabel setCenter:webview.center];
    //  [_loadingTipIndicator setFrame:CGRectMake(floor(_loadingTipLabel.frame.origin.x - _loadingTipIndicator.bounds.size.width - 5.0f), _loadingTipLabel.frame.origin.y, _loadingTipIndicator.bounds.size.width, _loadingTipLabel.bounds.size.height)];
    //全部居中
    float totalWidth = _loadingTipIndicator.width + 5.0f + _loadingTipLabel.width;
    float indicatorLeftMargin = floor((webview.width-totalWidth)/2.0f);
    _loadingTipIndicator.frame = CGRectMake(indicatorLeftMargin, _loadingTipLabel.top, _loadingTipIndicator.width, _loadingTipLabel.height);
    _loadingTipLabel.frame = CGRectMake(_loadingTipIndicator.right+5.0f, _loadingTipLabel.top, _loadingTipLabel.width, _loadingTipLabel.height);
    
    [_loadingTipIndicator setHidesWhenStopped:YES];
    [_loadingTipIndicator startAnimating];
}

- (void)dismissWebviewLoading:(UIView *)webview
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    UILabel *_loadingTipLabel = (UILabel *)[webview viewWithTag:3000];
    UIActivityIndicatorView *_loadingTipIndicator = (UIActivityIndicatorView *)[webview viewWithTag:3001];
    [_loadingTipLabel setHidden:YES];
    [_loadingTipIndicator stopAnimating];
}

- (void)showAlertWithMessage:(NSString *)msg completion:(dispatch_block_t)completion
{
    RIButtonItem *btnCancel = [RIButtonItem itemWithLabel:NSLocalizedString(@"OK", nil) action:completion];
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:msg cancelButtonItem:btnCancel otherButtonItems:nil];
    [alertView show];
}

- (void)showAlertWithMessage:(NSString *)msg
                      OtherChoice:(NSString *)otherChoice
                  completion:(dispatch_block_t)completion{
    RIButtonItem *btnCancel = [RIButtonItem itemWithLabel:NSLocalizedString(@"Cancel", nil) action:completion];
    RIButtonItem *btnItem = [RIButtonItem itemWithLabel:otherChoice action:completion];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:msg cancelButtonItem:btnCancel otherButtonItems:btnItem,nil];
    [alertView show];
}

- (void)backClick:(id)sender 
{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([[weakSelf.ownerViewController.navigationController viewControllers] count] > 1){
            [weakSelf.ownerViewController.navigationController popViewControllerAnimated:YES];
        }else{
            [weakSelf.ownerViewController dismissViewControllerAnimated:YES completion:nil];
        }
    });
}

#pragma clang diagnostic pop

@end
